package com.grj.blog.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    // 示例：修改 GlobalExceptionHandler.java 中的 handleException 方法
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public void handleException(HttpServletResponse response, Exception ex) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter(); // 确保此处未先调用 getOutputStream()
        writer.write("{\"error\":\"" + ex.getMessage() + "\"}");
        writer.flush();
        writer.close();
    }

}